package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@PropertySource("classpath:/image.properties")
public class FileServiceImpl implements FileService {
    //定义本地路径
    @Value("${image.localPathDir}")
    private String localPathDir;    // = "D:/JT_IMAGE"
    //定义url
    @Value("${image.localUrlPath}")
    private String localUrlPath;    // = "http://image.jt.com"
    /**
     *1.保证前端上传数据有效性
     *      1.1 校验文件名称，检查是否是图片  ——正则
     *      1.2 检验文件是否是恶意文件
     * @param file
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile file) throws IOException {
        //1.检验数据有效性     .jpg  .JPG
        String fileName = file.getOriginalFilename();
        fileName = fileName.toLowerCase();
        if (!fileName.matches("^.+\\.(jpg|png|gif|jpeg)$")){
            return null;
        }
        //1.2 校验图片类型是否是木马
        //bufferedImage对象是一个图片专用对象（前缀），其他对象信息装不进去
        BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
        //获取宽高
        int width = bufferedImage.getWidth();
        int height = bufferedImage.getHeight();
        if (width == 0 || height == 0){
            return null;
        }
        //2.实现文件上传
        //应当分目录存储。。。减少检索负担     以日期为目录  /yyyy/MM/dd/
        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
        //2.2 目录拼接
        //D://JT_IMAGE/2021/05/21/
        String localDir = localPathDir + datePath;
        //2.3 (若不存在)创建目录
        File dirFile = new File(localDir);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        //3. 解决文件名重复问题(UUID)
        //生成UUID
        String uuid = UUID.randomUUID().toString()
                .replace("-", "");
        //记录文件类型
        //.jpg
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        //拼接真正的文件名
        //uuid.jpg
        String realFileName = uuid + fileType;
        //拼接全路径
        //D://JT_IMAGE/2021/05/21/uuid.jpg
        String filePathAll = localDir + realFileName;
        //转换成路径
        File realFile = new File(filePathAll);
        //4. 上传文件
        file.transferTo(realFile);
        //5. 封装对象
        //2021/05/21/uuid.jpg
        String virtualPath = datePath + realFileName;
        //http://image.jt.com/2021/05/21/uuid.jpg
        String urlPath = localUrlPath + virtualPath;

        return new ImageVO(virtualPath,urlPath,realFileName);
    }
    //virtualPath: 2021/05/21/uuid.jpg
    //localPath: D://JT_IMAGE
    @Override
    public void fileRemove(String virtualPath) {
        String filePath = localPathDir + virtualPath;
        File file = new File(filePath);
        //执行删除
        file.delete();
    }
}
